﻿#region Header

/*
Remote views based on linq
By

Pascal Hauser 
Dipl. Ing. in Informatik, Hochschule für Technik Rapperswil, 2006
Master Thesis, Hochschule für Technik Rapperswil, 2008-2010

and

Raphael Gfeller
Dipl. Ing. in Informatik, Hochschule für Technik Rapperswil, 2006
Master Thesis, Hochschule für Technik Rapperswil, 2008-2010

*/

#endregion

#region Usings

using System;
using System.Collections.Generic;
using Sebarf.Diagnostics.Interfaces;
using Sebarf.Services.Interfaces;
using Sebastof.Services.Impl;
using Sebastof.Services.Interfaces;

#endregion

namespace Sebastof.Client.Services.Impl {
	/// <summary>
	/// uses the LazyLoadingDataHandlingStrategy to restore the data
	/// Impl of <see cref="IDataHandlingStrategyService"/>
	/// </summary>
	public class LazyLoadingSerializationDataHandlingStrategyService : Service, ISerializationDataHandlingStrategyService {
		#region Public Properties

		[ServiceRequest]
		public IObservableCollectionCreatorService ObservableCollectionCreatorService { get; set; }

		#endregion

		#region Public Methods

		public LazyLoadingSerializationDataHandlingStrategyService(
			IObservableCollectionCreatorService observableCollectionCreatorService) {
			ObservableCollectionCreatorService = observableCollectionCreatorService;
		}

		public LazyLoadingSerializationDataHandlingStrategyService() {
		}

		#endregion

		#region ISerializationDataHandlingStrategyService Members

		public Dictionary<string, object> GetDataToTransferFromObject(object obj) {
			throw new NotImplementedException();
		}

		public void RestoreObjectFromTransferedData(object obj, Dictionary<string, object> data) {
			Check.ArgumentNotNull(ObservableCollectionCreatorService, "ObservableCollectionCreatorService");
			var iObject = obj as ISebastofApplicationObject;
			Check.ArgumentNotNull(iObject, "iObject");
			Type genericType = iObject.GetType();

			if (obj is SebastofApplicationObject) {
				//  create generic type of the LazyLoadingDataHandlingStrategy
				Type enumerableType = typeof(LazyLoadingDataHandlingStrategy<>).MakeGenericType(genericType);
				// sets the lazy loading strategy
				(iObject as SebastofApplicationObject).UsedDataHandlingStrategy =
					(IDataHandlingStrategy)
					Activator.CreateInstance(enumerableType, new Object[] { iObject, ObservableCollectionCreatorService });
			}
			// restore transmitted values
			foreach (var item in data) {
				iObject.SetValue(item.Key, item.Value);
			}
		}

		#endregion
	}
}